﻿using Unity.Entities;
using Unity.Jobs;
using Unity.Transforms;

namespace Jinndev.ECS {

    /// <summary>
    /// 当销毁Parent实体时，自动销毁所有Child实体
    /// </summary>
    [UpdateInGroup(typeof(TransformSystemGroup), OrderFirst = true)]
    //[UpdateBefore(typeof(LocalToParentSystem))]
    public class DestroyChildrenSystem : JobComponentSystem {

        private EndSimulationEntityCommandBufferSystem commandBufferSystem;

        private EntityQuery entityQuery;

        protected override void OnCreate() {
            commandBufferSystem = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>();

            //entityQuery = GetEntityQuery(new EntityQueryDesc() {
            //    All = new ComponentType[] {
            //        ComponentType.ReadOnly<DestroyChildren>(),
            //        ComponentType.ReadOnly<Child>()
            //    },
            //    None = new ComponentType[] {
            //        ComponentType.ReadOnly<LocalToWorld>()
            //    }
            //});
        }

        protected override JobHandle OnUpdate(JobHandle inputDeps) {
            EntityCommandBuffer entityCommandBuffer = commandBufferSystem.CreateCommandBuffer();
            EntityCommandBuffer.ParallelWriter ecbc = entityCommandBuffer.AsParallelWriter();

            inputDeps = Entities.WithAll<DestroyChildren>().WithNone<LocalToWorld>().ForEach((int entityInQueryIndex, Entity entity, in DynamicBuffer<Child> children) => {
                for (int i = 0; i < children.Length; i++) {
                    Entity child = children[i].Value;
                    ecbc.DestroyEntity(entityInQueryIndex, child);
                }
            }).WithStoreEntityQueryInField(ref entityQuery).Schedule(inputDeps);
            commandBufferSystem.AddJobHandleForProducer(inputDeps);
            inputDeps.Complete();

            // 手动Playback，并禁用默认Playback
            entityCommandBuffer.Playback(EntityManager);
            entityCommandBuffer.ShouldPlayback = false;

            // 最终移除DestroyChildren，实现Entity的最终销毁
            EntityManager.RemoveComponent<DestroyChildren>(entityQuery);

            return inputDeps;
        }

    }

}
